package com.xyd.servlet;

import com.xyd.entity.Message;
import com.xyd.entity.User;
import com.xyd.service.CartService;
import com.xyd.service.impl.CartServiceImpl;
import com.xyd.util.CookieUtil;
import com.xyd.util.JsonUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：
 *
 * @author 张吉哲
 * @date 2021/1/13 11:01
 */
@WebServlet("/cartChangeNumServlet")
public class CartChangeNumServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute("user");
    Message message = new Message();
    if (user == null) {
      message.setFlag(false);
      message.setMessage("您尚未登陆，请登陆");
      return;
    }

    // 现在的商品数量
    String newNum = request.getParameter("newNum");
    String epId = request.getParameter("epId");

    boolean flag = true;
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
      if ((CookieUtil.getCookieName()).equals(cookie.getName())) {
        String value = cookie.getValue();
        StringBuilder newValue = new StringBuilder();
        String[] split = value.split("\\*");
        for (String s : split) {
          String[] split1 = s.split(",");
          if (split1[0].equals(epId)) {
            split1[1] = newNum;
            CartService cartService = new CartServiceImpl();
            flag = cartService.changeNum(user.getEuUserId(), split1[0], newNum);
          }
          newValue.append(split1[0]).append(",").append(split1[1]).append("*");
        }
        CookieUtil.fixCookie(cookie, newValue.toString(), response);
        break;
      }
    }
    message.setFlag(flag);
    JsonUtil.toJson(response, message);
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request, response);
  }
}
